//
//  LXSalaryApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/24.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXSalaryApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXRemarkTabelViewCell.h"
#import "LXSalaryModel.h"
#import "LXChooseBtnTableViewCell.h"

@interface LXSalaryApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;

@property (nonatomic) NSMutableArray *platformData;
@property (nonatomic) NSInteger platform;

@end

@implementation LXSalaryApplyViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    
    
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
    [self.tableView registerClass:[LXChooseBtnTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXChooseBtnTableViewCell class])];

    
    
    
    self.view.backgroundColor = White_Color;
    [self.view addSubview:self.tableView];
    
    [self loadData];
    
    if (self.type == 1) {
        [self setBottomViewWithText:@"确认新增"];
        [self layoutCustomNav:self.view title:@"添加平台返佣"];
    }
    else {
        [self setBottomViewWithText:@"确认修改"];
        [self layoutCustomNav:self.view title:@"修改平台返佣"];
    }
    
    
    
}
- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
    
    // 模型为空,说明从车辆详情进入
    if (!ObjectIsEmpty(self.salaryModel)) {

        // 车牌号
        [self.loanDic setValue:self.salaryModel.carNum forKey:@"carNum"];
        [self.loanDic setValue:self.salaryModel.model forKey:@"model"];
        [self.loanDic setValue:self.salaryModel.platform forKey:@"platform"];

        // 修改的时候需要带入数据
        if (self.type==2) {
            
            // 平台
            [self.loanDic setValue:self.salaryModel.platform forKey:@"platform"];
            //开始日期
            [self.loanDic setValue:self.salaryModel.startDate forKey:@"startDate"];
            //结束开始
            [self.loanDic setValue:self.salaryModel.endDate forKey:@"endDate"];
            // 返佣金额
            [self.loanDic setValue:[NSString toTen:self.salaryModel.amount] forKey:@"amount"];
            // 入账时间
            [self.loanDic setValue:self.salaryModel.paidDate forKey:@"paidDate"];
            // 备注
            [self.loanDic setValue:self.salaryModel.remark forKey:@"remark"];

        }

    }

    self.data = @[
         
           @{
               @"title":@"车牌号",
               @"key":@"carNum",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"品牌型号",
               @"key":@"model",
               @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"返佣平台",
               @"key":@"platform",
               @"height":self.type==1?@([LXChooseBtnTableViewCell height:self.platformData]):@(kComHeight),
           },
           
           @{
               @"title":self.type==1?@"*返佣统计开始日期":@"返佣统计开始日期",
               @"key":@"startDate",
               @"placeHolder" : @"请选择返佣统计开始日期",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"sel":self.type==1?@"clickBeginTimeAction":@"",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.type==1?@"*返佣统计结束日期":@"返佣统计结束日期",
               @"key":@"endDate",
               @"placeHolder" : @"请选择返佣统计结束日期",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"sel":self.type==1?@"clickEndTimeAction":@"",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.type==1?@"*返佣金额(元)":@"返佣金额(元)",
               @"key":@"amount",
               @"placeHolder" : @"请输入返佣金额",
               @"inputType":@(NUM_DECIMAL),
               @"keyboardType":@(UIKeyboardTypeDecimalPad),
               @"maxLength":@(7),
               @"sel":@"",
               @"showAccess":@(NO),
               @"canEdit":self.type==1?@(YES):@(NO),
               @"height":@(kComHeight)
           },
           @{
               @"title":@"*入账日期",
               @"key":@"paidDate",
               @"placeHolder" : @"请选择入账日期",
               @"sel":self.type==1?@"clickPaidTimeAction":@"",
               @"showAccess":self.type==1?@(YES):@(NO),
               @"canEdit":@(NO),
               @"height":@(kComHeight)
           },
           @{
               @"title":@"备注",
               @"key":@"remark",
               @"height":@(150)
           }
    ];
    

    
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.data count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.row];
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.row];
    if([dic[@"key"]  isEqualToString:@"remark"]){
        // 备注
        LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.textView.placeholder = @"请输入备注...";
        cell.textView.maxLength = 200;
        cell.remarkTitle.text = @"备注";
        cell.textView.text = self.loanDic[@"remark"];
        [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
            [self.loanDic setValue:textStr forKey:@"remark"];
        }];
        return cell;
    }
    // 返佣平台
   else if([dic[@"key"]  isEqualToString:@"platform"] && self.type == 1){
      LXChooseBtnTableViewCell *cell = [[LXChooseBtnTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([LXChooseBtnTableViewCell class]) WithData:self.platformData];

      cell.selectionStyle = UITableViewCellSelectionStyleNone;
      [cell setClipsToBounds:YES];
       cell.canEdit = YES;
      cell.titleLab.text = dic[@"title"];
       [cell setClickBtnWithBlock:^(NSString * _Nonnull str, NSInteger Id) {
           [self.loanDic setValue:str forKey:@"platform"];
           self.platform = Id;
           [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
       }];
      
      
      
      return cell;
   }
    
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    

    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
        
    };
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}




#pragma mark -- 选择开始日期
-(void)clickBeginTimeAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"startDate"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择返佣统计开始日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
        if([NSString compareDate:yearString withDate:self.loanDic[@"startDate"] withFormat:k_DateFormat]==-1){
            showAlert(@"开始日期不能大于结束日期");
        }
        else {
            [self.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
            [weakSelf.tableView reloadData];
        }
    };
}
#pragma mark -- 选择结束日期
-(void)clickEndTimeAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"endDate"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择佣统计结束日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
       

        if([NSString compareDate:yearString withDate:self.loanDic[@"startDate"] withFormat:k_DateFormat]==1){
            showAlert(@"结束日期不能小于开始日期");
        }
        else {
            [self.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
            [weakSelf.tableView reloadData];
        }

    };
}
#pragma mark -- 选择入账日期
-(void)clickPaidTimeAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"paidDate"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择入账日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
        [self.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
        [weakSelf.tableView reloadData];

    };
}


- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, kScreenHeight - kViewTopHeight - kComHeight - 10) style:UITableViewStylePlain];
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = ColorWithF7F8FA;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}




#pragma mark ---- 确认新增/修改点击事件
- (void)clickBottomView:(UIButton *)sender{
    
    if (StringIsEmpty(self.loanDic[@"platform"])) {
        showAlert(@"请选择返佣平台");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"startDate"])) {
        showAlert(@"请选择返佣统计开始日期");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"endDate"])) {
        showAlert(@"请选择返佣统计结束日期");
        return;
    }
   
    if (StringIsEmpty(self.loanDic[@"amount"])) {
        showAlert(@"请输入返佣金额");
        return;
    }
    if ([self.loanDic[@"amount"] doubleValue] == 0) {
        showAlert(@"返佣金额不能为0");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"paidDate"])) {
        showAlert(@"请选择入账日期");
        return;
    }
    
   
    
    [Tool showAlertTitle:@"是否确认提交" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        
        

        
        NSMutableDictionary *dic = @{
            
            @"carId":self.salaryModel.carId, // 所属车辆id
            @"carNum":self.salaryModel.carNum,// 所属车辆车牌号
            @"model":self.loanDic[@"model"], // 车型
            @"platform":self.loanDic[@"platform"], // 平台
            @"startDate":self.loanDic[@"startDate"], //  开始日期
            @"endDate":self.loanDic[@"endDate"], //  结束日期
            @"amount":self.loanDic[@"amount"], // 牌照金额
            @"paidDate":self.loanDic[@"paidDate"], //  入账时间
            @"remark":self.loanDic[@"remark"], //  备注
        
            
        }.mutableCopy;
        
        
        NSString *url;
        if (self.type == 1) {
            url = POST_AddTreturnbrokerage;
        }
        else
        {
            url = POST_UpdateTreturnbrokerage;
            [dic setValue:self.salaryModel.ID forKey:@"id"];
        }
        
        
        
        [MSNetworkManager postRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            
            if (isSuccess) {
                if (self.type==1) {
                    showAlert(@"新增返佣成功");
                }
                else {
                    showAlert(@"修改返佣成功");
                }
               
                
                // carModel 有值说明从详情页进入,返回时须刷新列表
                if (!ObjectIsEmpty(self.salaryModel)) {
                    kUserDefaultSetBool(YES, kRefreshStr);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:YES];
    } onVC:self];
    
 
}


#pragma mark -- 运行平台数据源
- (NSArray *)platformData{
    
    
    NSArray *operPlatformAry = [[NSUserDefaults standardUserDefaults] valueForKey:k_YXPT];
    
    _platformData = [NSMutableArray array];

    if (!ObjectIsEmpty(operPlatformAry)) {
        
        for (int i = 0; i<operPlatformAry.count; i++) {
            
            NSDictionary *mm = operPlatformAry[i];
            NSDictionary *dic = @{
                @"title":mm[@"label"],
                @"sel":@(NO),
                @"id":mm[@"value"],
            }.mutableCopy;
            [_platformData addObject:dic];
        }
    }
    
 
    for (NSMutableDictionary *dic in _platformData) {
        if ([dic[@"id"] intValue] == self.platform) {
            [dic setValue:@(YES) forKey:@"sel"];
            break;
        }
    }
    return _platformData;
}

@end
